/*
 * @Description: 
 * @Version: 1.0
 * @Autor: lairensi
 * @Date: 2021-08-31 12:03:46
 * @LastEditors: lairensi
 * @LastEditTime: 2021-08-31 12:51:29
 */

import 'package:flutter/material.dart';
import 'package:flutter_demo/api/user_service.dart';
import 'package:flutter_demo/config/home_menu.dart';
import 'package:flutter_demo/config/main_shared_preferences_key.dart';
import 'package:flutter_demo/provider/user_provider.dart';
import 'package:flutter_demo/util/global.dart';
import 'package:flutter_demo/widget/toast_msg.dart';
import 'dart:async';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:provider/provider.dart';

// 热跟新所需依赖
import 'package:flutter/foundation.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  // 动画控制器
  AnimationController _controller;
  Animation<double> animationNarrow;
  Animation<double> animationText;
  // 单位名称
  String companyName;
  // 打卡状态 0未到打卡时间 1可以打卡 2打卡完成 3打卡完后离岗 4未到达岗位
  int clockIn = 0;
  String clockName = '未到打卡时间';
  String clockDes = '好好休息，以更好的状态迎接下一次工作吧';

  // 存储班次信息 接班时需要
  var userInfoProvider;
  String sdlNumId;
  String companyId;
  int dutyArea;
  String location;


  // 初始化
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(seconds: 1),
      vsync: this,
    );
    _controller.addListener(() {
      setState(() => {});
    });
    animationNarrow = new Tween(begin: 0.0, end: 1.0)
        .animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut));
    animationText = new Tween(begin: 0.0, end: 1.0)
        .chain(CurveTween(curve: Interval(0.8, 1)))
        .animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut));

    getToken();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  getToken() async {
    userInfoProvider = Provider.of<UserInfoProvider>(context, listen: false);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var token = prefs.getString(MainSharedPreferencesKey.Token.toString());
    if (token == null) {
      Future.delayed(Duration(milliseconds: 100), () {
        Navigator.pushReplacementNamed(context, "/login");
      });
      return;
    }
    Global.TOKEN = token;
    // 在这里获取用户基本信息
    var userRes = await UserService.getUserinfo({});
    var userInfo = userRes["body"];
    // 更新provider userinfo
    userInfoProvider.changeUserName(userInfo);
  
  }




  @override
  Widget build(BuildContext context) {
    //填入设计稿中设备的屏幕尺寸
    ScreenUtil.init(context, width: 375, height: 667);
    var statusBarHeight = ScreenUtil.statusBarHeight;

    return Scaffold(
      body: Container(
        color: Color.fromRGBO(16, 16, 16, 1),
        padding: EdgeInsets.symmetric(vertical: 0, horizontal: 15.w),
        child:CustomScrollView(
            slivers: <Widget>[
              SliverList(
                delegate: SliverChildListDelegate([
                  Padding(
                      padding: EdgeInsets.fromLTRB(
                          0, statusBarHeight + 33, 0, 25.h),
                      child: Container(
                        width:163.w ,
                        height: 25.h,
                        decoration: new BoxDecoration(
                          image: new DecorationImage(
                            image:new AssetImage("lib/assets/images/home-logo.png"),
                            // fit: BoxFit.contain
                          )
                        ),
                        child:Row(
                          mainAxisAlignment:MainAxisAlignment.start,
                          children: [
                            GestureDetector(
                              child:Image.asset("lib/assets/images/telephone-book.png",width: 22.w,),
                              onTap: (){
                                //进入通讯录
                                Navigator.pushNamed(context, "/addressBook");
                              },
                            ),
                              
                          ],
                        ) ,
                  )),
                 
                ]),
              ),
              SliverGrid(
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                  maxCrossAxisExtent: 167.w,
                  mainAxisSpacing: 10.h,
                  crossAxisSpacing: 10.w,
                  childAspectRatio: 1.4, //子控件宽高比
                ),
                delegate: SliverChildListDelegate(this._getList(context)),
              ),
            ],
          ),
      ),
    );
  }



  // 菜单
  List<Widget> _getList(context) {
    return list.map((res) {
      return GestureDetector(
        onTap: () async {
          // 点击事件
          if (res['route'].toString().isNotEmpty) {
            if (res['route'] == '/login') {
              SharedPreferences prefs = await SharedPreferences.getInstance();
              prefs.setString(MainSharedPreferencesKey.Token.toString(), null);

              Navigator.pushReplacementNamed(context, "/login");
              return;
            }
            ToastMsg().showToastMsg(msg: res['name']);
            // Navigator.pushNamed(context, res['route']);
          } else {
            Navigator.pushNamed(context, "/test");
          }
        },
        child: Container(
            decoration: BoxDecoration(
                color: Color.fromRGBO(24, 24, 24, 1),
                borderRadius: BorderRadius.circular(4.0),
                image: res['background'] != null
                    ? new DecorationImage(
                        image: new AssetImage('lib/assets/images/${res['icon']}'),
                        //这里是从assets静态文件中获取的，也可以new NetworkImage(）从网络上获取
                        centerSlice:
                            new Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
                      )
                    : null),
            child: Stack(
              alignment: Alignment.center, //指定未定位或部分定位widget的对齐方式
              overflow: Overflow.clip,
              children: <Widget>[
                Positioned(
                    left: 15.w,
                    top: 15.h,
                    child: Text(res['name'],
                        style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                            color: Color.fromRGBO(6, 167, 116, 1)))),
                Positioned(
                    left: 15.w,
                    top: 35.h,
                    child: Text(res['des'],
                        style: TextStyle(
                            fontSize: 12.sp,
                            color: Color.fromRGBO(255, 255, 255, 0.3)))),
                res['notice'] != ''
                    ? Positioned(
                        right: 7.w,
                        top: 7.h,
                        child: Container(
                            width: 16.w,
                            height: 16.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: Color.fromRGBO(255, 91, 91, 1),
                              borderRadius: BorderRadius.circular(8.w),
                            ),
                            child: Text(res['notice'],
                                style: TextStyle(
                                    fontSize: 10.sp, color: Colors.white))))
                    : Container(),
                res['background'] == null
                    ? Positioned(
                        right: 0,
                        bottom: 0,
                        child: Image.asset(
                          'lib/assets/images/${res['icon']}',
                          height: 66.w,
                          fit: BoxFit.fill,
                        ))
                    : Text(""),
              ],
            )),
      );
    }).toList();
  }

}
